import * as PDFJS from 'pdfjs-dist/build/pdf';

import workerSrc from 'pdfjs-dist/build/pdf.worker';

PDFJS.GlobalWorkerOptions.workerSrc = workerSrc;

export const convertPdfToImageFn = async pdfUrl => {
  const pdf = await PDFJS.getDocument(pdfUrl).promise;

  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  const list: any = [];

  // // 循环遍历每一页pdf，将其转成图片
  for (let i = 1; i <= pdf._pdfInfo.numPages; i++) {
    // 获取pdf页
    const page = await pdf.getPage(i);

    // 获取页的尺寸
    const viewport = page.getViewport({ scale: 2 });

    // 设置canvas的尺寸
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // 将pdf页渲染到canvas上
    await page.render({ canvasContext: context, viewport: viewport }).promise;

    // 将canvas转成图片，并添加到页面上

    list.push(canvas.toDataURL('image/png'));
  }

  return list;
};
